import { useState } from 'react';
import { Button, Space, Form, Row, Col, Input, Table, Image, Popover, Modal } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import type { Feedback, QueryFeedbackListParams } from './services';
import { FeedbackStatus, dealFeedback, queryFeedbackList } from './services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import dayjs from 'dayjs';
import Ellipsis from '@/components/Ellipsis';
import { Access } from '@umijs/max';
import StationSelect from '@/components/StationSelect';
import type { OrgSettle } from '@/pages/moneySettle/orgSettle/services';
import { jump2target } from '@/utils/common';

const AppUserPage: React.FC = () => {
  const [dealForm] = Form.useForm()
  const [searchForm] = Form.useForm<QueryFeedbackListParams>()
  const [searchParams, setSearchParams] = useState<QueryFeedbackListParams>({
    pageNum: 1, pageSize: 10,
  })
  const feedbackList = useRequest(() => queryFeedbackList(searchParams), {
    refreshDeps: [searchParams],
  })
  const [imgList, setImgList] = useState<string[]>([])
  const delFeedbackReq = useRequest(dealFeedback, {manual: true})
  const [dealRecord, setDealRecord] = useState<Feedback>()

  const onFinish = (formValues: any) => {
    console.log(formValues)
    setSearchParams({
      ...searchParams,
      // stubGroupId: formValues.stubGroupId?.[0]?.id,
      title: formValues.station?.[0]?.name,
      stubId: formValues.stubId,
      orderId: formValues.orderId,
      pageNum: 1,
    })
  }

  const openDealModal = (record: Feedback) => {
    setDealRecord(record)
  }


  const openDetail = (id: string) => {
    jump2target(`/moneySettle/personSettle?settleId=${id}`, {needRefresh: true})
  }

  const onDealModalCancel = () => {
    dealForm.resetFields()
    setDealRecord(undefined)
  }

  const onDealModalOk = () => {
    dealForm
    .validateFields()
    .then((values: any) => {
      return delFeedbackReq.runAsync({
        infoId: dealRecord!.id,
        commend: values.commend,
      })
    })
    .then(() => {
      onDealModalCancel()
      feedbackList.refresh()
    })
  }

  const columns: ColumnsType<Feedback> = [
    {
      title: '私桩主',
      dataIndex: 'orgName',
      width: 120,
      render: val => val || '--'
    },
    {
      title: '电站名称',
      dataIndex: 'stationName',
      width: 120,
      render: val => val || '--'
    },

    {
      title: '应付金额',
      dataIndex: 'totalFee',
      width: 140,
    },
    {
      title: '生效时间',
      dataIndex: 'createTime',
      width: 140,
    },
    {
      title: '已付金额',
      dataIndex: 'payMoney',
      width: 140,
    },
    {
      title: '结算明细',
      dataIndex: 'settleIds',
      width: 160,
      render: (_, record) => {
        if (record.settleIds) {
          if (record.settleIds.indexOf(',') === -1) {
            return <div>
              <div onClick={() => openDetail(skill)} key={index}>{`结算明细: ${record.settleIds}`}</div>
            </div>
          }
          else {
            return record.settleIds.split(',').map((skill, index) => (
              <div onClick={() => openDetail(skill)} key={index} color="blue" style={{ margin: '2px' }}>
                结算明细: {skill.trim()} {/* 使用 trim() 去除可能的空格 */}
              </div>
            ))
          }
        } else {
          return <div>
            <div>--</div>
          </div>
        }
      }
    },

    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: val => val && FeedbackStatus[val]
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 80,
      fixed: 'right',
      render: (id: number, record) => {
        return <Space>
        <Access accessible={record.status === FeedbackStatus.付款中}>
          <a onClick={() => openDealModal(record)}>处理</a>
        </Access>
        <Access accessible={!!record.commend}>
          <Popover content={record.commend} trigger='click'>
            <a>查看</a>
          </Popover>
        </Access>
        </Space>
      }
    }
  ]
  
  return (
    <div className='container'>
      <div className="card search-card">
        <div className="form-area">
          <Form name='searchErrorForm' form={searchForm} onFinish={onFinish}>
            <Row gutter={[20, 20]}>
              {/* <Col span={6}>
                <Form.Item label='场站ID' name='stubGroupId'>
                  <StationSelect />
                </Form.Item>
              </Col> */}
              <Col span={6}>
                <Form.Item label='场站名称' name='station'>
                  <StationSelect allowClear inline />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='设备ID' name='stubId'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='订单ID' name='orderId'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={feedbackList.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<Feedback>
          rowKey='id'
          loading={feedbackList.loading}
          dataSource={feedbackList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: feedbackList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
      <Image.PreviewGroup
        items={imgList}
        preview={{
          visible: imgList.length > 0,
          onVisibleChange: val => {
            if (!val) setImgList([])
          }
        }}
      >
      </Image.PreviewGroup>
      <Modal
        title='手动处理费用'
        open={!!dealRecord}
        onCancel={onDealModalCancel}
        onOk={onDealModalOk}
        confirmLoading={delFeedbackReq.loading}
      >
        <Form form={dealForm} name='dealForm'>
          <Form.Item label='备注' name='commend'>
            <Input.TextArea placeholder="请输入" style={{width: '100%', height: 80}} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AppUserPage;
